import RPi.GPIO as GPIO
import time

class Stepper_Motor:

    def __init__(self,IN1,IN2,IN3,IN4):
        self.IN1 = IN1
        self.IN2 = IN2
        self.IN3 = IN3
        self.IN4 = IN4
        # init
        
        GPIO.setwarnings(False)
        # Set GPIO mode and configure pins
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.IN1, GPIO.OUT)
        GPIO.setup(self.IN2, GPIO.OUT)
        GPIO.setup(self.IN3, GPIO.OUT)
        GPIO.setup(self.IN4, GPIO.OUT)

        # Define constants
        self.DEG_PER_STEP = 1.8
        self.STEPS_PER_REVOLUTION = int(360 / self.DEG_PER_STEP)
        
    # Function to move the stepper motor one step anticlockwise
    def step_anticlockwise(self,delay, steps):
        for _ in range(steps):
            for coil in [self.IN1,self.IN2,self.IN3,self.IN4]:
                GPIO.output(coil, GPIO.HIGH)
                time.sleep(delay)
                GPIO.output(coil, GPIO.LOW)

    # Function to move the stepper motor one step clockwise
    def step_clockwise(self,delay, steps):
        for _ in range(steps):
            for coil in [self.IN4,self.IN3,self.IN2,self.IN1]:
                GPIO.output(coil, GPIO.HIGH)
                time.sleep(delay)
                GPIO.output(coil, GPIO.LOW)

      
if __name__ == "__main__":
    try:
        IN1 = 23
        IN2 = 24
        IN3 = 25
        IN4 = 8
        motor=Stepper_Motor(IN1,IN2,IN3,IN4)
        # Set the delay between steps
        delay = 0.005

        while True:
            # Rotate one revolution anticlockwise
            motor.step_anticlockwise(delay, motor.STEPS_PER_REVOLUTION)

            # Pause for 2 seconds
            time.sleep(2)

            # Rotate one revolution clockwise
            motor.step_clockwise(delay, motor.STEPS_PER_REVOLUTION)

            # Pause for 2 seconds
            time.sleep(2)

    except KeyboardInterrupt:
        print("\nExiting the script.")

    finally:
        # Clean up GPIO settings
        GPIO.cleanup()
   